use super::{update_map, Data};
use leptos::*;
use std::{collections::HashMap, rc::Rc};

#[allow(non_snake_case)]
#[component]
pub fn DatePicker(label: &'static str, #[prop(into)] name: String) -> impl IntoView {
    let (getter, setter) = use_context::<(
        ReadSignal<HashMap<String, Data>>,
        WriteSignal<HashMap<String, Data>>,
    )>()
    .expect("");
    let name = Rc::new(name);
    let value = {
        let name = Rc::clone(&name);
        move || {
            let map = getter.get();
            let value = map.get(name.as_str()).and_then(|v| v.str());
            value.map(|v| v.to_string()).unwrap_or_default()
        }
    };
    view! {
        <div class="flex flex-col gap-2">
            <label class="pl-2 text-lg">{label}</label>
            <input type="date" value=value on:change= move |ev| {
                let value = event_target_value(&ev);
                let name = name.as_ref();
                setter.update(|map| {
                if name.contains('.') {
                    update_map(name, value, map)
                }else {
                    let name = name.to_string();
                    map.insert(name,Data::String(value));
                }
                })
            } class="border border-solid rounded h-9 pl-2 outline-blue-400"/>
        </div>
    }
}
